package a01_数组;

/**
 * <p>
 * a06_螺旋矩阵2复习6
 * </p>
 *
 * @author flyduck
 * @since 2025/4/8
 */
public class a06_螺旋矩阵2复习6 {
    public int[][] generateMatrix(int n) {
        int[][] grid = new int[n][n];
        grid[0][0] = 1;
        String direction = "right";
        int x = 0;
        int y = 0;
        int num = 2;//需要赋值的数据

        while (num <= n * n){
            if("right".equals(direction)){
                if(y + 1 < n && grid[x][y+1] == 0){
                    grid[x][y+1] = num;
                    y++;
                    num++;
                }else {
                    direction = "down";
                }
            }

            if("down".equals(direction)){
                if(x + 1 < n && grid[x+1][y] == 0){
                    grid[x+1][y] = num;
                    x++;
                    num++;
                }else {
                    direction = "left";
                }
            }

            if("left".equals(direction)){
                if(y - 1 >= 0 && grid[x][y-1] == 0){
                    grid[x][y-1] = num;
                    y--;
                    num++;
                }else {
                    direction = "up";
                }
            }

            if("up".equals(direction)){
                if(x - 1 >= 0 && grid[x-1][y] == 0){
                    grid[x-1][y] = num;
                    x--;
                    num++;
                }else {
                    direction = "right";
                }
            }
        }
        return grid;
    }
}
